package com.gali.mall.service.impl;


import com.gali.mall.exception.GaLiException;
import com.gali.mall.exception.GaLiExceptionEnum;
import com.gali.mall.model.dao.UserMapper;
import com.gali.mall.model.pojo.User;
import com.gali.mall.service.UserService;
import com.gali.mall.utils.MD5Util;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class UserServiveImpl implements UserService {
@Autowired
 private  UserMapper userMapper;
    @Override
    public void register(User user) throws GaLiException {
        User user1 = userMapper.selectbyUsername(user.getUsername());
        if(user1!=null){
            throw new GaLiException(GaLiExceptionEnum.USER_EXISTED);
        }
           userMapper.insertSelective(user);
    }

    @Override
    public User login(String username, String password) throws GaLiException {
        String md5Pwd=null;
        try {
            md5Pwd= MD5Util.getMD5(password);
        }catch (Exception e){
            e.printStackTrace();
        }
        User user = userMapper.selectByUser(username, md5Pwd);
        if (user==null){
            throw  new GaLiException(GaLiExceptionEnum.WORN_LOGIN);
        }
        return user;
    }

    @Override
    public int updateToSignature(Integer id, String signature) {
        User user =new User();
        user.setId(id);
        user.setPersonalizedSignature(signature);
       Integer n = userMapper.updateByPrimaryKeySelective(user);
       if (n>1){
           try {
               throw new GaLiException(GaLiExceptionEnum.UPDATE_WORN);
           } catch (GaLiException e) {
               e.printStackTrace();
           }
       }
        return n;
    }

    @Override
    public User adminLogin(String username,String password) throws GaLiException {
        User user = userMapper.selectbyUsername(username);
        Integer role = user.getRole();
        if (role.equals(2)==false){
            try {
                throw new GaLiException(GaLiExceptionEnum.ADMIN_ERROR);
            } catch (GaLiException e) {
                e.printStackTrace();
            }
        }
        String md5 = MD5Util.getMD5(password);
        User user1 = userMapper.selectByUser(username, md5);
        if (user1==null){
            throw  new GaLiException(GaLiExceptionEnum.WORN_LOGIN);
        }
        return user1;
    }

    @Override
    public List<User> findAll() {
        return userMapper.selectAll();
    }
}
